﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PerformanceAssessment.Models;
using System.Data;

namespace PerformanceAssessment.Controllers
{
    public class SkillAssessmentsController : Controller
    {
        private PerformanceAssessmentDB db = new PerformanceAssessmentDB();

        [Authorize]
        public ActionResult Edit(int assessmentId, int order)
        {
            if (order < 0)
                return RedirectToAction("Details", "Assessments", new { assessmentId = assessmentId });

            Assessment assessment = db.Assessments.Include("Employee").Include("Manager").Include("Employee.Team").Where(a => a.ID == assessmentId).FirstOrDefault();
            int countSPT = db.SkillAssessments.Where(s => s.IdAssessment == assessmentId).Count();

            if (order >= countSPT)
                return RedirectToAction("Details", "Assessments", new { assessmentId = assessmentId });

            //Validates that the user can open this assessment
            UserModel user = UserModel.GetCurrentUser();
            if (assessment.AccessDenied(user))
                throw new AccessDeniedException();

            ViewBag.assessment = assessment;
            ViewBag.order = order;
            ViewBag.userType = user.UserType;
            SkillAssessment skillAssessment = (from s in db.SkillAssessments.Include("Skill")
                                               where s.DisplayOrder == order && s.IdAssessment == assessmentId
                                               select s).FirstOrDefault();

            return View(skillAssessment);
        }

        [HttpPost]
        [Authorize]
        public ActionResult Edit(SkillAssessment skillAssessment, int order, string btnBack, string btnNext)
        {
            Assessment assessment = db.Assessments.Include("Employee").Include("Manager").Include("Employee.Team").Where(a => a.ID == skillAssessment.IdAssessment).FirstOrDefault();
            UserModel user = UserModel.GetCurrentUser();
            if (ModelState.IsValid)
            {
                //Validates access to the assessment
                if (assessment.AccessDenied(user))
                    throw new AccessDeniedException();

                //Administrator cannot edit the assessment
                if (assessment.EditionAllowed(user.UserType, UserType.Employee, UserType.Manager))
                {
                    //Only saves the available columns depending on the user type. This is done in case of the user
                    //changing the disabled controls and adding its own scores or comments there
                    SkillAssessment saveSkillAssessment = db.SkillAssessments.Where(s => s.IdAssessment == skillAssessment.IdAssessment && s.IdSkill == skillAssessment.IdSkill).FirstOrDefault();
                    if (user.UserType == UserType.Employee)
                    {
                        if (skillAssessment.EmployeeScore == null)
                            ModelState.AddModelError("EmployeeScore", "The score must be specified");
                        else if (string.IsNullOrWhiteSpace(skillAssessment.EmployeeComments))
                            ModelState.AddModelError("EmployeeComments", "You must add some comments/examples to justify your score"); 
                        saveSkillAssessment.EmployeeScore = skillAssessment.EmployeeScore;
                        saveSkillAssessment.EmployeeComments = skillAssessment.EmployeeComments;
                    }
                    else
                    {
                        saveSkillAssessment.ManagerScore = skillAssessment.ManagerScore;
                        saveSkillAssessment.ManagerComments = skillAssessment.ManagerComments;
                    }
                    //It has to do another check for valid state since it might have been manually invalidated by code
                    if (ModelState.IsValid)
                    {
                        db.Entry(saveSkillAssessment).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }

                //It has to do another check for valid state since it might have been manually invalidated by code
                if (ModelState.IsValid)
                {
                    if (btnBack != null)
                        return RedirectToAction("Edit", new { assessmentId = skillAssessment.IdAssessment, order = order - 1 });
                    else if (btnNext != null)
                        return RedirectToAction("Edit", new { assessmentId = skillAssessment.IdAssessment, order = order + 1 });
                }
            }

            ViewBag.assessment = assessment;
            ViewBag.order = order;
            ViewBag.userType = user.UserType;
            skillAssessment.Skill = db.Skills.Where(s => s.ID == skillAssessment.IdSkill).FirstOrDefault();
            return View(skillAssessment);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
